<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Menu;
use app\lib\exception\LoginException;
use app\lib\exception\SuccessMessage;
use think\Request;
use app\lib\validate\AddAdmin;
use \app\admin\model\Setting as SettingModel;
use app\admin\model\Log;

class Setting extends Base{
    public function index() {

        return view();
    }

    //管理员统计
    public function admin() {
        $list = Admin::where(array('status' => 1))->paginate(20);
        $this->assign('list', $list);
        return view();
    }

    //添加管理人员
    public function add() {
        if(Request::instance()->post()) {
            (new AddAdmin())->goCheck();//检验参数是否合法
            $data = Request::instance()->post();
            $data['pwd'] = MD5(Request::instance()->post('pwd'));
            $data['add_id'] = session('admin_id');
            $data['add_time'] = date("Y-m-d");
            $data['add_name'] = session('admin_name');

            if(!empty(Admin::Where(array('mobile' => $data['mobile']))->find())) {
                throw new LoginException([
                    'msg' => '该手机号码已存在'
                ]);
            }

            $db = new Admin();
            $res = $db->insert($data);

            if($res) {
                throw new SuccessMessage([
                    'msg' => '添加成功'
                ]);
            }else {
                throw new LoginException([
                    'msg' => '添加失败'.$this->error()
                ]);
            }
        }

        $this->assign('detail', '');
        return view();
    }

    //删除管理员
    public function del() {
        if(Request::instance()->post()) {
            $id = intval(Request::instance()->post('id'));
            if(Admin::where(array('id' => $id))->update(array('status' => 0))) {
                throw new SuccessMessage([
                    'msg' => '删除成功'
                ]);
            }else {
                throw new LoginException([
                    'msg' => '删除失败'
                ]);
            }
        }
    }

    //菜单管理
    public function menu() {
        $list = Menu::paginate(10);
        $this->assign('list', $list);
        return view();
    }
    public function log()
    {
        $list = Log::with(['admin'])->paginate(10);
        
        $this->assign('list', $list);
        return view();
    }
}